<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <!-- 条件查询区域 -->
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="账号：">
              <a-input placeholder="请输入账户" allowClear v-model="queryParam.userId"/>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="合格证编号：">
              <a-input placeholder="请输入合格证编号" allowClear v-model="queryParam.code"/>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="主体名称：">
              <a-input placeholder="请输入主体名称" allowClear v-model="queryParam.companyName"/>
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus">
            <a-col :span="6">
              <a-form-item label="产品名称：">
                <a-input placeholder="请输入产品名称" allowClear v-model="queryParam.productName"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="检验机构：">
                <a-input placeholder="请输入检验机构" allowClear v-model="queryParam.testBy"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <!--基于官方封装组件方式（组件会自行加载字典数组数据）-->
              <a-form-item label="检测方式：">
                <j-dict-select-tag placeholder='请选择检测方式' dictCode='test_type' v-model="queryParam.testType"/>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="开具日期：">
                <j-date placeholder="请输入开始日期" v-model="queryParam.dateBegin"></j-date>
                -
                <j-date placeholder="请输入结束日期" v-model="queryParam.dateEnd"></j-date>
              </a-form-item>
            </a-col>
          </template>

          <a-col :span="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
      <!--操作按钮区域-->
      <a-row>
        <a-col :span="24">
          <a-button type="primary" icon="download">导出</a-button>
          <!--有勾选时才显示批量操作按钮-->
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1">
                <a-icon type="delete" @click="batchDel"/>
                删除
              </a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px">
              批量操作
              <a-icon type="down"/>
            </a-button>
          </a-dropdown>
        </a-col>
      </a-row>
      <!--表格数据区域-->
      <a-row style="margin-top: 30px">
        <a-col :span="24">
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-table
            bordered
            size="middle"
            rowKey="id"
            :dataSource="tableData"
            :pagination="ipagination"
            :loading="loading"
            :scroll="{ x: 3000 }"
            :rowSelection="{fixed : true,selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
            <a-table-column title="账号" data-index="userId" align="center" width="120px"/>
            <a-table-column title="生产主体" data-index="companyName" align="center" width="120px"/>
            <a-table-column title="法人名称" data-index="legalPersonName" align="center" width="120px"/>
            <a-table-column title="省" data-index="province" align="center" width="100px"/>
            <a-table-column title="市" data-index="city" align="center" width="120px"/>
            <a-table-column title="区/县" data-index="area" align="center" width="160px"/>
            <a-table-column title="乡镇/街道" data-index="country" align="center" width="160px"/>
            <a-table-column title="详细地址" data-index="detailAddress" align="center" width="260px"/>
            <a-table-column title="生产地址" data-index="produceAddress" align="center" width="260px"/>
            <a-table-column title="产品名称" data-index="productName" align="center" width="260px"/>
            <a-table-column title="重量(数量)" data-index="productWeight" align="center" width="260px"/>
            <a-table-column title="单位"  align="center" width="260px">
              <template slot-scope="text,record,index">
                {{getUnitStr(text.unit)}}
              </template>
            </a-table-column>
            <a-table-column title="合格方式" align="center" width="260px">
              <template slot-scope="text,record,index">
                {{getTestTypeStr(text.testType)}}
              </template>
            </a-table-column>
            <a-table-column title="检验机构" data-index="testBy" align="center" width="260px"/>
            <a-table-column title="检测报告" data-index="testReport" align="center" width="260px">
              <template slot-scope='text'>
                <span v-if='!text || text.trim() ===""' style='font-size: 12px;font-style: italic;'>无文件</span>
                <span v-else-if='isImage(text)'>
            <img @click='imgClickView(text)' :src='getImgView(text)' height='25px' alt='' style='max-width:80px;font-size: 12px;font-style: italic;cursor: pointer;'/>
                  <!--多图片点击预览组件-->
            <duo-image-viewer :list="imgSrcList" @update:show="handleClose" :show="showViewer" :currentIndex="currentIndex"/>
          </span>
                <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadClick(text)">
                  下载
                </a-button>
              </template>
            </a-table-column>
            <a-table-column title="开具日期" data-index="createTime" align="center" width="260px"/>
            <a-table-column title="合格证编号" data-index="code" align="center" width="260px"/>
            <a-table-column title="打印次数" data-index="printNumber" align="center" width="260px"/>
            <a-table-column title="操作" fixed="right"  align="center" width="260px">
              <template slot-scope="text,record,index">
                <a href="javascript:;">编辑</a>
                <a-divider type="vertical" />
                <a-dropdown>
                  <a class="ant-dropdown-link">
                    更多 <a-icon type="down"/>
                  </a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a href="javascript:;">详情</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm title="确定删除吗?">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </a-table-column>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </a-card>
</template>

<script>
//定义引入的js插件
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDate from '@/components/jeecg/JDate'
//引入JS方法
import {getAction} from '@/api/manage';
import {filterDictTextByCache} from '@/components/dict/JDictSelectUtil'

export default {
  components: {
     JDictSelectTag, JDate
  },
  data() {
    return {
      /*** 多图片查看 start*/
      currentIndex: 0, // 打开图片查看器时，需要定位到的图片的索引
      imgSrcList: [], // 图片查看器数据集
      showViewer: false, // 是否打开图片查看器
      /*** 多图片查看 end*/
      //存放查询条件数据（当前页面查询条件组件双向绑定使用，以及传入省市区组件中实现双向绑定）
      queryParam: {},
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 表格数据源 */
      tableData: [],
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      //页面所有事件请求后端接口地址
      url: {
        list: "/njt-certificate/list",
      },
    }
  },
  methods: {
    // 判断是否是图片
    isImage(path) {
      const imgFormat = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
      for (let j = 0; j < imgFormat.length; j++) {
        if (path.lastIndexOf(imgFormat[j]) > -1) {
          return true
        }
      }
      return false
    },
// 官方默认的downloadFile方法只能打开单个文件，但是项目实际需求中可能会存在同时多个pdf，所以需要重新定义downloadClick方法
// pdf下载点击事件
    downloadClick(text) {
      let arrays = text.split(',')
      // 打开多个pdf
      for (let i = 0; i < arrays.length; i++) {
        // 直接在浏览器窗口打开
        window.open(arrays[i])
      }
    },
    /* 图片加载预览 */
    imgClickView(text){
      // 将图片路径处理一下
      let srcArray = text.split(",")
      let srcAllArray= []
      srcArray.forEach((temp)=>{
        srcAllArray.push(this.getImgView(temp))
      })
      this.imgSrcList = srcAllArray;
      this.showViewer = !this.showViewer
    },
    // 多图片查看器打开
    handleOpen() {
      this.showViewer = !this.showViewer
    },
    // 多图片查看器关闭
    handleClose() {
      this.showViewer = false
    },
    //解决数据库存储多张图片，表格默认显示第一张
    getImgView(text){
      if(text && text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      return text;
    },
    //使用字典渲染表格列方法
    getUnitStr(val) {
      return filterDictTextByCache('unit_type', val);
    },
    getTestTypeStr(val) {
      return filterDictTextByCache('test_type', val);
    },
    //数据加载
    loadData(pageNum) {
      //给查询条件新增分页参数
      this.queryParam.pageNo = pageNum;
      this.queryParam.pageSize = this.ipagination.pageSize;
      this.loading = true;//开启加载特效
      getAction(this.url.list, this.queryParam).then((res) => {
        if (res.success) {
          //将响应数据复制表格显示
          this.tableData = res.result.records;
          //将响应的分页数据赋值表格分页参数
          this.ipagination.total = res.result.total;
        }
        this.loading = false;//关闭特效，渲染数据
      })
    },
    //批量操作菜单
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel();
      }
    },
    //批量删除操作方法
    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {

          }
        });
      }
    },
    //表格复选框选中事件
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    //清空复选框选中
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    //分页条筛选变化时触发
    handleTableChange(pagination) {
      //将新的分页条数据赋值给原数据对象（这样才能实现页码选中切换）
      this.ipagination = pagination;
      this.loadData(pagination.current)
    },
    //查询操作
    searchQuery(){
      this.loadData(1);
    },
    //清空所有查询条件
    searchReset() {
      // 借助双向绑定数据对象清空组件数据
      this.queryParam = {};
      this.loadData(1);
    },
    //切换查询条件的折叠
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },

  },
  created() {
    this.loadData(1);

  },

}
</script>